package com.zyg.apart.controller;


import com.github.pagehelper.PageInfo;
import com.zyg.apart.model.User;
import com.zyg.apart.service.RoleService;
import com.zyg.apart.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @RequestMapping("/list")
    public String list(Integer currentPage, Model model){
        if (currentPage == null){
            currentPage = 1;
        }
        PageInfo<Map<String,Object>> users = userService.getAllUsers(currentPage);
        model.addAttribute("users",users);
        return "user/list";
    }

    @RequestMapping("/detail")
    public String detail(Model model,Integer id){
        Map<String,Object> user = userService.getUserById(id);
        model.addAttribute("user",user);
        return "user/detail";
    }

    @RequestMapping("/toEdit")
    public String toEdit(Model model, Integer id){
        Map<String,Object> user = userService.getUserById(id);
        List<Map<String,Object>> roles = roleService.getAllRoleName();
        model.addAttribute("user",user);
        model.addAttribute("roles",roles);
        return "user/edit";
    }

    @RequestMapping("/edit")
    public String edit(User user ){
        int i = userService.editUser(user);
        return "forward:list";
    }

    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        List<Map<String,Object>> roles = roleService.getAllRoleName();
        model.addAttribute("roles",roles);
        return "user/add";
    }

    @RequestMapping("/add")
    public String add(User user){
        int i = userService.addUser(user);
        return "forward:list";
    }

    @RequestMapping("/del")
    public String del(Integer id){
        int i = userService.delUserById(id);
        return "forward:list";
    }
}
